import uuid
from dataclasses import asdict
from urllib.parse import urlparse, parse_qs

from selenium.webdriver.chrome import webdriver
from selenium.webdriver.common.by import By
from functional import seq
from spider_h5.seleinum_bankend.pages.sec_level.applet_page import AppletPage
from spider_h5.seleinum_bankend.pojo.goods_base import GoodsBase
from spider_h5.seleinum_bankend.pojo.goods_detail import SpecValueItem, SpecDetail, GoodsDetail
from spider_h5.seleinum_bankend.utils.mongo_utils import DBRoc

"""
Description: 小程序的管理页面
Note: 1. 这里的商品详情信息是根据获取在数据库中的商品列表信息的编辑URL而来的，获取某个店铺的商品详情信息时一定要保证商品列表信息已经被持久化
Warning: 1. 在此之下的页面不再进行具体区分，全部都放置在此类下面；2.关于异常处理的部分，后续再进行整合
Todo: 1. 对于菜品详情的分类部分无法获取，怎么获取到Select下的选中Selected的Option
"""


class AppletManagePage(object):
    """
    关于小程序的管理页面
    """

    def __init__(self, client):
        self.client = client
        self.browser: webdriver = client.browser
        self.goods_list = 'goods_list'
        self.goods_detail = 'goods_detail'
        self.setmeal_list = 'setmeal_list'
        self.setmeal_detail = 'setmeal_detail'

    """
    商品管理
    """

    """商品列表"""

    def gain_goods_list(self, applet_id):
        """
        获取商品详情数据
        Params:
        -applet_id:小程序ID
        """

        self.browser.find_element(By.XPATH, '/html/body/div[1]/div[1]/ul[1]/li[4]').click()  # 切换至商品页面
        self.browser.find_element(By.XPATH, '/html/body/div[1]/div[1]/ul[2]/li/a[1]').click()  # 切换至商品列表
        goods_dict_list = []
        while True:
            goods_list = self.browser.find_elements(By.XPATH, '/html/body/div[1]/div[2]/div/div/div/div/div[2]/div[2]/table/tbody/tr')
            for record in goods_list:
                _id = str(uuid.uuid4())
                code = record.find_element(By.XPATH, './td[1]').text
                applet_id = applet_id
                img_url = record.find_element(By.XPATH, './td[2]/a').get_attribute('href') if len(record.find_elements(By.XPATH, './td[2]/a')) > 0 else ""
                name = record.find_element(By.XPATH, './td[3]/p').text
                category = record.find_element(By.XPATH, './td[5]').text
                sale_num = record.find_element(By.XPATH, './td[6]').text
                price = record.find_element(By.XPATH, './td[7]').text
                spec = record.find_element(By.XPATH, './td[8]').text.strip()
                state = record.find_element(By.XPATH, './td[10]').text.strip()
                create_time = record.find_element(By.XPATH, './td[12]').text
                edit_url = record.find_element(By.XPATH, './td[13]//a[1]').get_attribute('href')
                goods_base = GoodsBase(_id=_id, code=code, applet_id=applet_id, img_url=img_url, name=name, category=category, sale_num=sale_num, price=price, spec=spec, state=state,
                                       create_time=create_time,
                                       edit_url=edit_url)
                goods_dict_list.append(goods_base.to_dict())
                print(goods_base.to_dict())
            element = self.browser.find_element(By.XPATH, '/html/body/div[1]/div[2]/div/div/div/div/div[2]/div[3]/div[1]/ul/li[last()]')
            class_name = element.get_attribute('class')
            if class_name == 'disabled':
                break
            else:
                url = element.find_element(By.XPATH, './a').get_attribute('href')
                self.browser.get(url)
        # 保存至数据库
        DBRoc(name=self.goods_list).insert_many(goods_dict_list)

    def gain_goods_detail(self, applet_id):
        """
        获取商品详情
        Params:
        -applet_id:小程序ID
        """
        records = DBRoc(self.goods_list).find_many(data={'applet_id': applet_id})
        goods_edit_url_list = seq(list(records)).map(lambda x: x['edit_url']).to_list()
        insert_goods_list = []
        for record in goods_edit_url_list:
            # 基础信息获取
            self.browser.get(record)
            # 解析 URL,获取参数
            shop_id = parse_qs(urlparse(record).query)['shop_id'][0]
            goods_name = self.browser.find_element(By.XPATH, '//*[@id="tab1"]/div/div[1]/div/input').get_attribute('value')
            goods_simple = self.browser.find_element(By.XPATH, '//*[@id="tab1"]/div/div[2]/div/input').get_attribute('value')
            goods_code = self.browser.find_element(By.XPATH, '//*[@id="tab1"]/div/div[3]/div/input').get_attribute('value')
            making_code = self.browser.find_element(By.XPATH, '//*[@id="tab1"]/div/div[4]/div/input').get_attribute('value')
            goods_img_url = self.browser.find_element(By.XPATH, '//*[@id="tab1"]/div/div[6]/div/div[1]/div/div/a').get_attribute('href')
            basic_price = self.browser.find_element(By.CSS_SELECTOR, '#base_price').get_attribute('value')
            takeout_price = self.browser.find_element(By.CSS_SELECTOR, '#takeaway_price').get_attribute('value')
            selling_point = self.browser.find_element(By.XPATH, '//*[@id="tab1"]/div/div[9]/div/input').get_attribute('value')
            # goods_category = self.browser.find_element(By.XPATH, '//*[@id="tab1"]/div/div[5]/div/select/option[selected]').text.strip()
            # 规格信息获取
            spec_list_elements = self.browser.find_elements(By.CSS_SELECTOR, '#many-app > div > div.spec-attr.list>div')
            spec_list = []
            for item in spec_list_elements:
                spec_name = item.find_element(By.XPATH, './/div[@class="spec-group-name"]/span').text
                spec_item_list = item.find_elements(By.XPATH, './/div[@class="spec-list am-cf"]/div[@class="spec-item"]')
                specdata_list = []
                for spec in spec_item_list:
                    spec_value = spec.find_element(By.XPATH, './div[1]/span').text
                    spec_simple = spec.find_element(By.XPATH, './div[2]/input').get_attribute('value')
                    list_price = spec.find_element(By.XPATH, './div[3]/input').get_attribute('value')
                    sale_price = spec.find_element(By.XPATH, './div[4]/input').get_attribute('value')
                    inventory = spec.find_element(By.XPATH, './div[5]/input').get_attribute('value')
                    specdata_list.append(SpecValueItem(spec_value=spec_value, spec_simple=spec_simple, list_price=list_price, sale_price=sale_price, inventory=inventory))
                spec_list.append(SpecDetail(spec_name=spec_name, spec_value_items=specdata_list))
            # 标签和过敏原获取
            tag_elements = self.browser.find_elements(By.XPATH, '//*[@id="tags-list"]/div')
            tag_list = []
            if len(tag_elements) > 0:
                for tag in tag_elements:
                    tag_list.append(tag.text.strip())
            allergens_elements = self.browser.find_elements(By.XPATH, '//*[@id="allergens-list"]/div')
            allergens_list = []
            if len(allergens_elements) > 0:
                for allergens in allergens_elements:
                    allergens_list.append(allergens.text.strip())
            status = self.browser.find_element(By.XPATH, '//*[@id="tab4"]/div[1]/div/label/input[@checked]/..').get_attribute("textContent").strip()
            good_status = True if status == '上架' else False
            recommend_tag = self.browser.find_element(By.XPATH, '//*[@id="tab4"]/div[2]/div/label/input[@checked]/..').get_attribute("textContent").strip()
            is_recommend = True if recommend_tag == '是' else False
            required_tag = self.browser.find_element(By.XPATH, '//*[@id="tab4"]/div[3]/div/label/input[@checked]/..').get_attribute("textContent").strip()
            is_required = True if required_tag == '是' else False
            only_pos_tag = self.browser.find_element(By.XPATH, '//*[@id="tab4"]/div[5]/div/label/input[@checked]/..').get_attribute("textContent").strip()
            is_only_pos = True if only_pos_tag == '是' else False
            goods_detail = GoodsDetail(applet_id=applet_id, shop_id=shop_id, goods_name=goods_name, goods_simple=goods_simple, goods_code=goods_code, goods_img_url=goods_img_url,
                                       basic_price=basic_price,
                                       takeout_price=takeout_price,
                                       selling_point=selling_point, spec_record=spec_list, goods_tag_list=tag_list, allergen_list=allergens_list, good_status=good_status, is_recommend=is_recommend,
                                       is_required=is_required, is_only_pos=is_only_pos, making_code=making_code, goods_category='')
            insert_goods_list.append(asdict(goods_detail))
            print(asdict(goods_detail))
        DBRoc(self.goods_detail).insert_many(insert_goods_list)

        """套餐列表""" \
 \
        """
        订单管理
        """ \
 \
        """
        用户管理
        """ \
 \
        """
        营销管理
        """ \
 \
        """
        设置
        """

    def gain_setmeal_list(self, applet_id):
        """
        获取套餐列表
        Params:
        -applet_id:小程序ID
        """
        self.browser.find_element(By.XPATH, '/html/body/div[1]/div[1]/div[1]/ul/li[3]').click()  # 切换到商品页
        self.browser.find_element(By.XPATH, '/html/body/div[1]/div[1]/div[2]/ul/li[2]').click()  # 切换到套餐页
        pass
